{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial 06, case 8: Navier-Stokes problem with Neumann control\n",
    "\n",
    "In this tutorial we solve the optimal control problem\n",
    "\n",
    "$$\\min J(y, u) = \\frac{1}{2} \\int_{\\Omega} |v - v_d|^2 dx + \\frac{\\alpha}{2} \\int_{\\Gamma_2} |u|^2 ds$$\n",
    "s.t.\n",
    "$$\\begin{cases}\n",
    "- \\nu \\Delta v + v \\cdot \\nabla v + \\nabla p = f       & \\text{in } \\Omega\\\\\n",
    "                                \\text{div} v = 0       & \\text{in } \\Omega\\\\\n",
    "                                           v = 0       & \\text{on } \\Gamma_1\\\\\n",
    "                       pn - \\nu \\partial_n v = u       & \\text{on } \\Gamma_2\\\\\n",
    "                                           v = 0       & \\text{on } \\Gamma_3\\\\\n",
    "                                           v = 0       & \\text{on } \\Gamma_4\n",
    "\\end{cases}$$\n",
    "\n",
    "where\n",
    "$$\\begin{align*}\n",
    "& \\Omega                      & \\text{unit square}\\\\\n",
    "& \\Gamma_1                    & \\text{bottom boundary of the square}\\\\\n",
    "& \\Gamma_2                    & \\text{left boundary of the square}\\\\\n",
    "& \\Gamma_3                    & \\text{top boundary of the square}\\\\\n",
    "& \\Gamma_4                    & \\text{right boundary of the square}\\\\\n",
    "& u \\in [L^2(\\Gamma_2)]^2     & \\text{control variable}\\\\\n",
    "& v \\in [H^1(\\Omega)]^2       & \\text{state velocity variable}\\\\\n",
    "& p \\in L^2(\\Omega)           & \\text{state pressure variable}\\\\\n",
    "& \\alpha > 0                  & \\text{penalization parameter}\\\\\n",
    "& v_d                         & \\text{desired state}\\\\\n",
    "& \\nu                         & \\text{kinematic viscosity}\\\\\n",
    "& f                           & \\text{forcing term}\n",
    "\\end{align*}$$\n",
    "using an adjoint formulation solved by a one shot approach"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from mpi4py import MPI\n",
    "from petsc4py import PETSc\n",
    "import sympy\n",
    "from ufl import derivative, div, grad, inner, Measure, replace, TestFunction, TrialFunction\n",
    "from dolfinx import Constant, DirichletBC, Function, FunctionSpace, VectorFunctionSpace\n",
    "from dolfinx.fem import locate_dofs_topological\n",
    "from dolfinx.io import XDMFFile\n",
    "from dolfinx.plot import create_vtk_topology\n",
    "from multiphenicsx.fem import (assemble_matrix_block, assemble_scalar, assemble_vector_block,\n",
    "                               BlockVecSubVectorWrapper, create_vector_block, create_matrix_block,\n",
    "                               DofMapRestriction)\n",
    "import pyvista"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mesh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with XDMFFile(MPI.COMM_WORLD, \"data/square.xdmf\", \"r\") as infile:\n",
    "    mesh = infile.read_mesh()\n",
    "    mesh.topology.create_connectivity_all()\n",
    "    subdomains = infile.read_meshtags(mesh, name=\"subdomains\")\n",
    "    boundaries = infile.read_meshtags(mesh, name=\"boundaries\")\n",
    "boundaries_134 = boundaries.indices[np.isin(boundaries.values, (1, 3, 4))]\n",
    "boundaries_2 = boundaries.indices[boundaries.values == 2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define associated measures\n",
    "dx = Measure(\"dx\")(subdomain_data=subdomains)\n",
    "ds = Measure(\"ds\")(subdomain_data=boundaries)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def dolfinx_to_pyvista_mesh(mesh):\n",
    "    num_cells = mesh.topology.index_map(mesh.topology.dim).size_local\n",
    "    cell_entities = np.arange(num_cells, dtype=np.int32)\n",
    "    pyvista_cells, cell_types = create_vtk_topology(mesh, mesh.topology.dim, cell_entities)\n",
    "    grid = pyvista.UnstructuredGrid(pyvista_cells, cell_types, mesh.geometry.x)\n",
    "    return grid"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pyvista_mesh_plot(mesh):\n",
    "    grid = dolfinx_to_pyvista_mesh(mesh)\n",
    "    plotter = pyvista.PlotterITK()\n",
    "    plotter.add_mesh(grid)\n",
    "    plotter.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_mesh_plot(mesh)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Function spaces"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Y_velocity = VectorFunctionSpace(mesh, (\"Lagrange\", 2))\n",
    "Y_pressure = FunctionSpace(mesh, (\"Lagrange\", 1))\n",
    "U = VectorFunctionSpace(mesh, (\"Lagrange\", 2))\n",
    "Q_velocity = Y_velocity.clone()\n",
    "Q_pressure = Y_pressure.clone()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Restrictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dofs_Y_velocity = np.arange(0, Y_velocity.dofmap.index_map.size_local + Y_velocity.dofmap.index_map.num_ghosts)\n",
    "dofs_Y_pressure = np.arange(0, Y_pressure.dofmap.index_map.size_local + Y_pressure.dofmap.index_map.num_ghosts)\n",
    "dofs_U = locate_dofs_topological(U, boundaries.dim, boundaries_2)\n",
    "dofs_Q_velocity = dofs_Y_velocity\n",
    "dofs_Q_pressure = dofs_Y_pressure\n",
    "restriction_Y_velocity = DofMapRestriction(Y_velocity.dofmap, dofs_Y_velocity)\n",
    "restriction_Y_pressure = DofMapRestriction(Y_pressure.dofmap, dofs_Y_pressure)\n",
    "restriction_U = DofMapRestriction(U.dofmap, dofs_U)\n",
    "restriction_Q_velocity = DofMapRestriction(Q_velocity.dofmap, dofs_Q_velocity)\n",
    "restriction_Q_pressure = DofMapRestriction(Q_pressure.dofmap, dofs_Q_pressure)\n",
    "restriction = [restriction_Y_velocity, restriction_Y_pressure, restriction_U,\n",
    "               restriction_Q_velocity, restriction_Q_pressure]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Trial and test functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(dv, dp) = (TrialFunction(Y_velocity), TrialFunction(Y_pressure))\n",
    "(w, q) = (TestFunction(Y_velocity), TestFunction(Y_pressure))\n",
    "du = TrialFunction(U)\n",
    "r = TestFunction(U)\n",
    "(dz, db) = (TrialFunction(Q_velocity), TrialFunction(Q_pressure))\n",
    "(s, d) = (TestFunction(Q_velocity), TestFunction(Q_pressure))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(v, p) = (Function(Y_velocity), Function(Y_pressure))\n",
    "u = Function(U)\n",
    "(z, b) = (Function(Q_velocity), Function(Q_pressure))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " ### Problem data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "alpha = 1.e-5\n",
    "x, y = sympy.symbols(\"x[0], x[1]\")\n",
    "psi_d = 10 * (1 - sympy.cos(0.8 * np.pi * x)) * (1 - sympy.cos(0.8 * np.pi * y)) * (1 - x)**2 * (1 - y)**2\n",
    "v_d_x = sympy.lambdify([x, y], psi_d.diff(y, 1))\n",
    "v_d_y = sympy.lambdify([x, y], - psi_d.diff(x, 1))\n",
    "v_d = Function(Y_velocity)\n",
    "v_d.interpolate(lambda x: np.stack((v_d_x(x[0], x[1]), v_d_y(x[0], x[1])), axis=0))\n",
    "nu = 0.1\n",
    "ff = Constant(mesh, (0., 0.))\n",
    "bc0 = Function(Y_velocity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optimality conditions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "F = [nu * inner(grad(z), grad(w)) * dx + inner(grad(w) * v, z) * dx\n",
    "     + inner(grad(v) * w, z) * dx - b * div(w) * dx + inner(v - v_d, w) * dx,\n",
    "     - q * div(z) * dx,\n",
    "     alpha * inner(u, r) * ds(2) - inner(z, r) * ds(2),\n",
    "     nu * inner(grad(v), grad(s)) * dx + inner(grad(v) * v, s) * dx - p * div(s) * dx\n",
    "     - inner(ff, s) * dx - inner(u, s) * ds(2),\n",
    "     - d * div(v) * dx]\n",
    "dF = [[derivative(F_i, u_j, du_j) for (u_j, du_j) in zip((v, p, u, z, b), (dv, dp, du, dz, db))] for F_i in F]\n",
    "dF[3][3] = Constant(mesh, 0.) * inner(dz, s) * (ds(1) + ds(3) + ds(4))\n",
    "bdofs_Y_velocity_134 = locate_dofs_topological((Y_velocity, Y_velocity), mesh.topology.dim - 1, boundaries_134)\n",
    "bdofs_Q_velocity_134 = locate_dofs_topological((Q_velocity, Y_velocity), mesh.topology.dim - 1, boundaries_134)\n",
    "bc = [DirichletBC(bc0, bdofs_Y_velocity_134, Y_velocity),\n",
    "      DirichletBC(bc0, bdofs_Q_velocity_134, Q_velocity)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Cost functional"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "J = 0.5 * inner(v - v_d, v - v_d) * dx + 0.5 * alpha * inner(u, u) * ds(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Class for interfacing with SNES"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class NonlinearBlockProblem(object):\n",
    "    def __init__(self, F, dF, solutions, bcs, restriction=None):\n",
    "        self._F = F\n",
    "        self._dF = dF\n",
    "        self._obj_vec = create_vector_block(F, restriction)\n",
    "        self._solutions = solutions\n",
    "        self._bcs = bcs\n",
    "        self._restriction = restriction\n",
    "\n",
    "    def update_solutions(self, x):\n",
    "        x.ghostUpdate(addv=PETSc.InsertMode.INSERT, mode=PETSc.ScatterMode.FORWARD)\n",
    "        with BlockVecSubVectorWrapper(x, [c.function_space.dofmap for c in self._solutions],\n",
    "                                      self._restriction) as x_wrapper:\n",
    "            for x_wrapper_local, component in zip(x_wrapper, self._solutions):\n",
    "                with component.vector.localForm() as component_local:\n",
    "                    component_local[:] = x_wrapper_local\n",
    "\n",
    "    def obj(self, snes, x):\n",
    "        self.F(snes, x, self._obj_vec)\n",
    "        return self._obj_vec.norm()\n",
    "\n",
    "    def F(self, snes, x, F_vec):\n",
    "        self.update_solutions(x)\n",
    "        with F_vec.localForm() as F_vec_local:\n",
    "            F_vec_local.set(0.0)\n",
    "        assemble_vector_block(F_vec, self._F, self._dF, self._bcs, x0=x, scale=-1.0,\n",
    "                              restriction=self._restriction, restriction_x0=self._restriction)\n",
    "\n",
    "    def dF(self, snes, x, dF_mat, _):\n",
    "        dF_mat.zeroEntries()\n",
    "        if self._restriction is None:\n",
    "            restriction = None\n",
    "        else:\n",
    "            restriction = (self._restriction, self._restriction)\n",
    "        assemble_matrix_block(dF_mat, self._dF, self._bcs, diagonal=1.0,\n",
    "                              restriction=restriction)\n",
    "        dF_mat.assemble()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Uncontrolled functional value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create problem by extracting state forms from the optimality conditions\n",
    "F_state = [replace(F[i], {s: w, d: q, u: Constant(mesh, (0, 0))}) for i in (3, 4)]\n",
    "dF_state = [[derivative(Fs_i, u_j, du_j) for (u_j, du_j) in zip((v, p), (dv, dp))] for Fs_i in F_state]\n",
    "dF_state[1][1] = Constant(mesh, 0) * dp * q * dx\n",
    "bc_state = [bc[0]]\n",
    "problem_state = NonlinearBlockProblem(F_state, dF_state, (v, p), bc_state)\n",
    "F_vec_state = create_vector_block(F_state)\n",
    "dF_mat_state = create_matrix_block(dF_state)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solve\n",
    "vp = create_vector_block([F[j] for j in (0, 1)])\n",
    "snes = PETSc.SNES().create(mesh.mpi_comm())\n",
    "snes.setTolerances(max_it=20)\n",
    "snes.getKSP().setType(\"preonly\")\n",
    "snes.getKSP().getPC().setType(\"lu\")\n",
    "snes.getKSP().getPC().setFactorSolverType(\"mumps\")\n",
    "snes.setObjective(problem_state.obj)\n",
    "snes.setFunction(problem_state.F, F_vec_state)\n",
    "snes.setJacobian(problem_state.dF, J=dF_mat_state, P=None)\n",
    "snes.setMonitor(lambda _, it, residual: print(it, residual))\n",
    "snes.solve(None, vp)\n",
    "problem_state.update_solutions(vp)  # TODO can this be safely removed?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "J_uncontrolled = mesh.mpi_comm().allreduce(assemble_scalar(J), op=MPI.SUM)\n",
    "print(\"Uncontrolled J =\", J_uncontrolled)\n",
    "assert np.isclose(J_uncontrolled, 0.1784542)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pyvista_scalar_field_plot(mesh, scalar_field, name):\n",
    "    grid = dolfinx_to_pyvista_mesh(mesh)\n",
    "    grid.point_arrays[name] = scalar_field.compute_point_values()\n",
    "    grid.set_active_scalars(name)\n",
    "    plotter = pyvista.PlotterITK()\n",
    "    plotter.add_mesh(grid)\n",
    "    plotter.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pyvista_vector_field_plot(mesh, vector_field, name, factor):\n",
    "    grid = dolfinx_to_pyvista_mesh(mesh)\n",
    "    values = np.zeros((mesh.geometry.x.shape[0], 3))\n",
    "    values[:, :2] = vector_field.compute_point_values()\n",
    "    grid.point_arrays[name] = values\n",
    "    grid.set_active_vectors(name)\n",
    "    plotter = pyvista.PlotterITK()\n",
    "    plotter.add_mesh(grid)\n",
    "    glyphs = grid.glyph(orient=name, factor=factor)\n",
    "    plotter.add_mesh(glyphs)\n",
    "    plotter.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_vector_field_plot(mesh, v, \"uncontrolled state velocity\", factor=1e-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_scalar_field_plot(mesh, p, \"uncontrolled state pressure\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optimal control"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create problem associated to the optimality conditions\n",
    "problem = NonlinearBlockProblem(F, dF, (v, p, u, z, b), bc, restriction)\n",
    "F_vec = create_vector_block(F, restriction=restriction)\n",
    "dF_mat = create_matrix_block(dF, restriction=(restriction, restriction))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solve\n",
    "vpuzb = create_vector_block(F, restriction=restriction)\n",
    "snes = PETSc.SNES().create(mesh.mpi_comm())\n",
    "snes.setTolerances(max_it=20)\n",
    "snes.getKSP().setType(\"preonly\")\n",
    "snes.getKSP().getPC().setType(\"lu\")\n",
    "snes.getKSP().getPC().setFactorSolverType(\"mumps\")\n",
    "snes.setObjective(problem.obj)\n",
    "snes.setFunction(problem.F, F_vec)\n",
    "snes.setJacobian(problem.dF, J=dF_mat, P=None)\n",
    "snes.setMonitor(lambda _, it, residual: print(it, residual))\n",
    "snes.solve(None, vpuzb)\n",
    "problem.update_solutions(vpuzb)  # TODO can this be safely removed?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "J_controlled = mesh.mpi_comm().allreduce(assemble_scalar(J), op=MPI.SUM)\n",
    "print(\"Optimal J =\", J_controlled)\n",
    "assert np.isclose(J_controlled, 0.1249381)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_vector_field_plot(mesh, v, \"state velocity\", factor=1e-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_scalar_field_plot(mesh, p, \"state pressure\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_vector_field_plot(mesh, u, \"control\", factor=1e-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_vector_field_plot(mesh, z, \"adjoint velocity\", factor=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pyvista_scalar_field_plot(mesh, b, \"adjoint pressure\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython"
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
